<template>
    <div>
      <n-card :bordered="false">
        <n-space style="margin-bottom: 10px">
          <n-select
              style="width: 300px"
              v-model:value="taskInfoQueryForm.taskType"
              :options="taskTypeOption"
              placeholder="请选择任务类型"
              clearable>
          </n-select>
          <n-select
              style="width: 300px"
              v-model:value="taskInfoQueryForm.resourceId"
              :options="resourceOption"
              :render-label="renderLabel"
              placeholder="请选择资源"
              clearable>
          </n-select>

          <n-button type="primary" :on-click="loadCommonTaskList">查询</n-button>
        </n-space>
      </n-card>
      <n-card style="margin-top: 5px" :bordered="false">
        <n-space justify="start">
          <n-button type="error" style="margin-bottom: 10px;" @click="batchTerminal">
            批量终止
          </n-button>
          <n-h5 v-if="checkedRowKeysRef.length>0"> 你选中了 {{ checkedRowKeysRef.length }} 行。 </n-h5>
        </n-space>
        <n-data-table
            :columns="columns"
            :data="commonTaskList"
            :loading="tableLoading"
            :row-key="row => row.id"
            v-model:checked-row-keys="checkedRowKeysRef"
            :style="{ height: `${clientHeight - (layoutHeaderHeight  + tabsHeight + 225)}px` }"
            flex-height
        >
        </n-data-table>
      </n-card>

    </div>
</template>

<script lang="ts" setup>
import {h, onMounted, reactive, ref} from 'vue'
import {NButton, NTag} from "naive-ui"
import {taskinfoController} from "@/api/controller/taskinfo/taskinfoController"
import {resourceController} from "@/api/resource/resourceController.api"

const {
  clientHeight,
  layoutHeaderHeight,
  darkTheme,
  tabsHeight
} = storeToRefs(useSystemStore());
import {storeToRefs} from "pinia"
import {useSystemStore} from "@/store/modules/useSystemStore"

const commonTaskList = ref([])

const formRef = ref(null)
const tableLoading = ref(false)
const resourceOption = ref([])
const taskTypeOption = ref([])
const checkedRowKeysRef = ref([])


const taskInfoQueryForm = reactive({
    taskType:null,
    resourceId: null
})

const tableTotal = ref(0)
const paginationReactive = reactive({
    page: 1,
    pageSize: 15,
    pageSizes: [15,30]
})

const onPageSizeChange = (pageSize: number) => {
    paginationReactive.pageSize = pageSize
}

const onPageChange = (page: number) => {
    paginationReactive.page = page
}

const loadCommonTaskList = () =>{
  tableLoading.value = true
  taskinfoController.getTaskInfoList(taskInfoQueryForm,{
    page: paginationReactive.page,
    pageSize: paginationReactive.pageSize
  }).then(res=>{
    if(res.code === 200){
      commonTaskList.value = res.data
    }
  }).finally(()=>{
    tableLoading.value = false
  })
}

/***
 * 获取绘画资源
 */
const getResourceInfo = async () => {
  const res = await resourceController.getSDResource('ALL');
  if (res.code === 200) {
    res.data.forEach((item: any) => {
      // @ts-ignore
      resourceOption.value.push({
        label: item.resourceName,
        value: item.id,
        type: item.type,
      });
    });
  }
}

const getTaskType = () => {
  taskinfoController.getTaskType().then(res => {
    if(res.code === 200){
      taskTypeOption.value = res.data
    }
  })
}


const renderLabel = (option: any) => {
  if (option.type == null || option.type.length == 0) {
    return option.label
  }
  return option.label + ' 【类型:' + option.type + '】'
}

// utils/dateUtils.js

const formatLongToDate = (longValue:number) =>{

  if(longValue == null){
    return ''
  }
  const date = new Date(longValue);
  // 使用日期对象的方法获取年、月、日等信息，然后拼接成想要的格式
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}


onMounted(()=>{
  getResourceInfo()
  getTaskType()
  loadCommonTaskList()
})


const columns = [
  {
    type: 'selection'
  },
   {
        title: '类型',
        key: 'taskType'
    },{
        title: '状态',
        key: 'taskStatus',
        render: function (row){
          if(row.taskStatus === 'NOT_START'){
            return h(NTag, {type: 'info'}, {default: () => '未启动'})
          }else if(row.taskStatus === 'SUBMITTED'){
            return h(NTag, {type: 'info'}, {default: () => '已提交'})
          }else if(row.taskStatus === 'SUCCESS'){
            return h(NTag, {type: 'success'}, {default: () => '已完成'})
          }else if(row.taskStatus === 'FAILURE'){
            return h(NTag, {type: 'error'}, {default: () => '已完成'})
          }else if(row.taskStatus === 'IN_PROGRESS'){
            return h(NTag, {type: 'primary'}, {default: () => '正在执行'})
          }
        }
    },{
      title: '提交时间',
      key: 'submitTime',
      render: function (row){
        return formatLongToDate(row.submitTime)
      }
    },{
        title: '开始时间',
        key: 'startTime',
        render: function (row){
          return formatLongToDate(row.startTime)
        }
    },{
      title: '结束时间',
      key: 'finishTime',
      render: function (row){
        return formatLongToDate(row.finishTime)
      }
    },{
        title: '操作',
        key: 'action',
        render (row:any) {
            return h(
                NButton,
                {
                    size: 'small',
                    type: 'error',
                    onClick: () => {
                        taskinfoController.terminalTask(row).then(res=>{
                          if(res.code === 200){
                            loadCommonTaskList()
                          }
                        })
                    }
                },
                { default: () => '终止' }
            )
        }
    }
]





const batchTerminal = () =>{
  let records = checkedRowKeysRef.value
  checkedRowKeysRef.value = []
  console.log(checkedRowKeysRef.value)
  if(records.length === 0){
    return
  }
  const selectList = commonTaskList.value.filter((item:any)=>{
    if(records.includes(item.id)){
      return true
    }
  })
  taskinfoController.batchTerminalTask(selectList).then(res=>{
    if(res.code === 200){
      loadCommonTaskList()
    }
  })
}


</script>

